package com.wzy.vx.controller;

import com.wzy.vx.Utils.ResuletVoUtils;
import com.wzy.vx.VO.ProductInfoVo;
import com.wzy.vx.VO.ProductVo;
import com.wzy.vx.VO.ResultVo;
import com.wzy.vx.dataobject.ProductCategory;
import com.wzy.vx.dataobject.ProductInfo;
import com.wzy.vx.repository.ProductCategoryRepository;
import com.wzy.vx.service.CategoryService;
import com.wzy.vx.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: vx
 * @Package: com.wzy.vx.controller
 * @ClassName: ButerProductController
 * @Author: Administrator
 * @Description: ${description}
 * @Date: 2019/3/12 15:06
 * @Version: 1.0
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    @Cacheable(cacheNames = "product",key = "123")
    public  ResultVo list(){
        //遍历插入数据

        //1.查询所有上架产品
        List<ProductInfo> productInfoList = productService.findUpAll();

        //2.查询类目 一次性
//        List<Integer> categoryList = new ArrayList<>();
//        for (ProductInfo productInfo:productInfoList) {
//            categoryList.add(productInfo.getCategoryType());
//        }
        //lomback
        List<Integer> categoryList = productInfoList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryList);

        //3.数据拼装
        List<ProductVo> productVoList = new ArrayList<>();
        for (ProductCategory productCate:productCategoryList) {
            ProductVo productVo = new ProductVo();
            productVo.setCategorType(productCate.getCategoryType());
            productVo.setCategoryName(productCate.getCategoryName());
            //分类
            List<ProductInfoVo> productInfoVoList1 = new ArrayList<>();
            for (ProductInfo productinfo:productInfoList) {
                if (productinfo.getCategoryType().equals(productCate.getCategoryType())) {
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productinfo, productInfoVo);
                    productInfoVoList1.add(productInfoVo);
                }
            }
            productVo.setCategoryFoods(productInfoVoList1);
            productVoList.add(productVo);
        }
        return ResuletVoUtils.success(productVoList);
    }
}
